package com.hyf.okhttp3demo.activity;

import android.Manifest;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebHistoryItem;
import android.widget.Button;
import android.widget.TextView;

import com.hyf.okhttp3demo.Config;
import com.hyf.okhttp3demo.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class DownLoadFileActivity extends AppCompatActivity {

    private static final int RC_WRITE_SD_CARD = 144;

    private static final int DOLOADING = 0;
    private static final int DOWNLOAD_COMPELTED = 1;


    private Button mButton;
    private TextView mTextView;

    private OkHttpClient mOkHttpClient;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_down_load_file);
        mButton = (Button) findViewById(R.id.btn_start_download);
        mTextView = (TextView) findViewById(R.id.tv_result);
        mOkHttpClient = new OkHttpClient();
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startDownLoad();
            }
        });

    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == DOLOADING) {
                String progress = "已下载" + msg.obj + "%";
                mTextView.setText(progress);
            } else if (msg.what == DOWNLOAD_COMPELTED) {
                String result = (String) msg.obj;
                mTextView.setText(result);
            }
        }
    };


    @AfterPermissionGranted(RC_WRITE_SD_CARD)
    public void startDownLoad() {
        String[] pers = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, pers)) {
            Request request = new Request.Builder()
                    .url(Config.API.URL_GET_DOWNLOAD_FILE)
                    .build();
            mOkHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Message message = mHandler.obtainMessage(DOWNLOAD_COMPELTED, e.getLocalizedMessage());
                    mHandler.sendMessage(message);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    writeFile(response);
                }
            });
        } else {
            EasyPermissions.requestPermissions(this, "申请获取读写权限", RC_WRITE_SD_CARD, pers);
        }
    }

    private void writeFile(Response response) {
        InputStream is = response.body().byteStream();
        FileOutputStream fos = null;
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "binjiang_9.apk");
        if (file.exists()) {
            file.delete();
        }
        try {
            fos = new FileOutputStream(file);
            byte[] bytes = new byte[1024];
            int length = 0;
            long sum = 0;
            long totle = response.body().contentLength();
            while ((length = is.read(bytes)) != -1) {
                fos.write(bytes, 0, length);
                sum += length;
                int progress = (int) ((sum * 1.0 / totle) * 100);
                Message message = mHandler.obtainMessage(DOLOADING, String.format("%02d", progress));
                mHandler.sendMessage(message);
            }
            fos.flush();
            Message message = mHandler.obtainMessage(DOWNLOAD_COMPELTED, "下载完毕");
            mHandler.sendMessage(message);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
